package org.goodsence.frammework.common.utils;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationContextException;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @author zty
 * @version 1.0.0
 * @apiNote 上下文工具类
 * @project_name modern-arranged-marriage
 * @user tain
 * @create_at 2023/4/14 1:07
 * @create_vio IntelliJ IDEA
 */
@Component
public final class ApplicationContextUtils implements ApplicationContextAware {

    private static ApplicationContext applicationContext;

    private ApplicationContextUtils() {

    }

    /**
     * SpringApplication 启动后 是否通过此方法设置上下文?
     * @param applicationContext
     * @throws BeansException
     */
    @Override
    public final void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        ApplicationContextUtils.applicationContext = applicationContext;
    }

    public static ApplicationContext getApplicationContext() {
        if (applicationContext == null) {
            throw new ApplicationContextException("上下文环境为空！");
        }
        return applicationContext;
    }

    public static Object getBean(String beanName) {
        return getApplicationContext().getBean(beanName);
    }

    public static HttpServletRequest getHttpServletRequest() {
        return getServletRequestAttributes().getRequest();
    }

    private static ServletRequestAttributes getServletRequestAttributes() throws IllegalStateException {
        ServletRequestAttributes attributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
        if (attributes == null) {
            throw new IllegalStateException("servletRequestAttributes is null!");
        }
        return attributes;
    }

    public static <T> T getBean(Class<T> clazz) {
        return getApplicationContext().getBean(clazz);
    }

    public static HttpSession getSession() {
        return getHttpServletRequest().getSession();
    }

    public static HttpServletResponse getHttpServletResponse() throws IllegalStateException {
        HttpServletResponse response = getServletRequestAttributes().getResponse();
        if (response == null){
            throw new IllegalStateException("httpServletResponse is null!");
        }
        return response;
    }
}
